<template>
  <div class="sales-container">
    <!-- 顶部标题 -->
    <h1 class="page-title">产品销售排行榜</h1>

    <!-- 前三名名柱子区域 -->
    <div class="top3-pillars">
      <!-- 第二名柱子（左侧） -->
      <div class="pillar-item second-pillar">
        <div class="rank-text">第二名</div>
        <div class="pillar-body">
          <div class="product-info">
            <p class="brand">韩束</p>
            <p class="name">口红</p>
            <p class="price">单价：¥200</p>
            <p class="total">总金额：600w</p>
          </div>
        </div>
      </div>

      <!-- 第一名柱子（中间） -->
      <div class="pillar-item first-pillar">
        <div class="rank-text">第一名</div>
        <div class="pillar-body">
          <div class="product-info">
            <p class="brand">资生堂</p>
            <p class="name">补水面膜</p>
            <p class="price">单价：¥100</p>
            <p class="total">总金额：800w</p>
          </div>
        </div>
      </div>

      <!-- 第三名柱子（右侧） -->
      <div class="pillar-item third-pillar">
        <div class="rank-text">第三名</div>
        <div class="pillar-body">
          <div class="product-info">
            <p class="brand">兰蔻</p>
            <p class="name">眼霜</p>
            <p class="price">单价：¥50</p>
            <p class="total">总金额：400w</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 标签栏 -->
    <el-tabs 
      v-model="activeTab" 
      class="sales-tabs"
      @tab-change="handleTabChange"
    >
      <el-tab-pane label="单品销售排行榜" name="single" />
      <el-tab-pane label="套装销售排行榜" name="set" />
      <el-tab-pane label="项目销售排行榜" name="project" />
    </el-tabs>

    <!-- 筛选栏 -->
    <div class="filter-container">
      <el-radio-group 
        v-model="activeDate" 
        class="date-filter"
        @change="handleDateChange"
      >
        <el-radio-button label="today">今日</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
      </el-radio-group>

      <div class="search-container">
        <span class="search-label">产品名称:</span>
        <el-input 
          v-model="searchKeyword" 
          class="search-input"
          placeholder="请输入产品名称"
        />
        <el-button 
          type="primary" 
          class="search-btn"
          @click="handleSearch"
        >
          查询
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="pagedData" 
      border 
      class="sales-table"
    >
      <el-table-column prop="rank" label="销售排名" />
      <el-table-column prop="name" label="产品名称" />
      <el-table-column prop="code" label="产品编号" />
      <el-table-column prop="spec" label="产品规格" />
      <el-table-column prop="brand" label="品牌归属" />
      <el-table-column prop="sales" label="销售数量" />
      <el-table-column prop="amount" label="销售总金额" />
      <el-table-column prop="discount" label="折扣总金额" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button 
            class="detail-btn"
            @click="openDetail(scope.row)"
          >
            明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="filteredData.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 明细弹窗（补充完整内容） -->
    <el-dialog 
      v-model="detailVisible" 
      title="产品销售明细" 
      width="1200px"
    >
      <!-- 弹窗顶部筛选区 -->
      <div class="dialog-filter" style="margin-bottom: 20px; display: flex; gap: 15px; align-items: center;">
        <el-date-picker 
          v-model="dialogStartTime" 
          type="date" 
          placeholder="开始时间" 
          style="width: 180px;"
        />
        <el-date-picker 
          v-model="dialogEndTime" 
          type="date" 
          placeholder="结束时间" 
          style="width: 180px;"
        />
        <el-button 
          type="primary" 
          style="background-color: #00b42a; border-color: #00b42a;"
          @click="filterDetailData"
        >
          查询
        </el-button>
        <el-button 
          type="danger" 
          @click="exportDetailData"
        >
          导出
        </el-button>
      </div>

      <!-- 产品基本信息 -->
      <div class="product-base-info" style="margin-bottom: 20px; padding: 15px; background: #f5f5f5; border-radius: 6px;">
        <div style="display: flex; flex-wrap: wrap; gap: 30px;">
          <p><span style="font-weight: bold;">产品名称：</span>{{ currentProduct?.name || '' }}</p>
          <p><span style="font-weight: bold;">产品编号：</span>{{ currentProduct?.code || '' }}</p>
          <p><span style="font-weight: bold;">产品规格：</span>{{ currentProduct?.spec || '' }}</p>
          <p><span style="font-weight: bold;">品牌归属：</span>{{ currentProduct?.brand || '' }}</p>
          <p><span style="font-weight: bold;">总销售数量：</span>{{ totalBuyNum }}</p>
          <p><span style="font-weight: bold;">总销售金额：</span>{{ totalRetailPrice }}</p>
          <p><span style="font-weight: bold;">总成交价：</span>{{ totalDealPrice }}</p>
        </div>
      </div>

      <!-- 明细表格 -->
      <div class="detail-content" v-if="currentProduct">
        <el-table 
          :data="filteredDetails" 
          border 
          stripe 
          size="small"
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center', backgroundColor: '#f5f5f5' }"
        >
          <el-table-column prop="date" label="日期" width="100" />
          <el-table-column prop="orderNo" label="订单号" width="120" />
          <el-table-column prop="productName" label="产品名称" width="120" />
          <el-table-column prop="productNo" label="产品编号" width="120" />
          <el-table-column prop="spec" label="规格" width="80" />
          <el-table-column prop="retailPrice" label="零售价" width="100" />
          <el-table-column prop="discount" label="折扣" width="80" />
          <el-table-column prop="discountPrice" label="折扣价" width="100" />
          <el-table-column prop="buyer" label="购买店家" width="120" />
          <el-table-column prop="contact" label="联系人" width="100" />
          <el-table-column prop="phone" label="联系电话" width="120" />
          <el-table-column prop="buyNum" label="购买数量" width="100" />
          <el-table-column prop="retailTotal" label="零售总价" width="100" />
          <el-table-column prop="dealPrice" label="成交价" width="100" />
          <el-table-column prop="payment" label="支付方式" width="100" />
        </el-table>

        <!-- 合计行 -->
        <div class="detail-total" style="margin-top: 10px; padding: 10px; text-align: right; font-weight: 500; color: #333;">
          筛选后总计：购买数量 {{ filteredBuyNum }} 件 | 零售总价 {{ filteredRetailPrice }} | 成交价 {{ filteredDealPrice }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';

// 状态管理
const activeTab = ref('single');
const activeDate = ref('week');
const searchKeyword = ref('');
const detailVisible = ref(false);
const currentProduct = ref(null);

// 弹窗内筛选状态
const dialogStartTime = ref('');
const dialogEndTime = ref('');
const filteredDetails = ref([]);

// 分页状态
const currentPage = ref(1);
const pageSize = ref(5);

// 模拟数据（补充弹窗所需字段）
const tableData = {
  single: {
    today: Array.from({ length: 15 }, (_, i) => ({ 
      rank: i + 1, 
      name: i % 3 === 0 ? '韩束精华液' : i % 3 === 1 ? '韩束补水面膜' : '韩束BB霜', 
      code: `HS-00${i % 3 + 1}`, 
      spec: i % 3 === 0 ? '50ml' : i % 3 === 1 ? '10片' : '30g', 
      brand: '韩束', 
      sales: 1200 + i * 100, 
      amount: `¥${(120000 + i * 10000).toLocaleString()}`, 
      discount: `¥${(12000 + i * 1000).toLocaleString()}`,
      // 补充完整明细字段
      details: [
        {
          date: '2024.06.08',
          orderNo: 'XS20240608001',
          productName: i % 3 === 0 ? '韩束精华液' : i % 3 === 1 ? '韩束补水面膜' : '韩束BB霜',
          productNo: `HS-00${i % 3 + 1}`,
          spec: i % 3 === 0 ? '50ml' : i % 3 === 1 ? '10片' : '30g',
          retailPrice: i % 3 === 0 ? '¥198' : i % 3 === 1 ? '¥128' : '¥98',
          discount: '8.5折',
          discountPrice: i % 3 === 0 ? '¥168' : i % 3 === 1 ? '¥109' : '¥83',
          buyer: '陈泽美容院',
          contact: '陈泽',
          phone: '13800138000',
          buyNum: 20,
          retailTotal: i % 3 === 0 ? '¥3960' : i % 3 === 1 ? '¥2560' : '¥1960',
          dealPrice: i % 3 === 0 ? '¥3360' : i % 3 === 1 ? '¥2180' : '¥1660',
          payment: '微信支付'
        },
        {
          date: '2024.06.09',
          orderNo: 'XS20240609002',
          productName: i % 3 === 0 ? '韩束精华液' : i % 3 === 1 ? '韩束补水面膜' : '韩束BB霜',
          productNo: `HS-00${i % 3 + 1}`,
          spec: i % 3 === 0 ? '50ml' : i % 3 === 1 ? '10片' : '30g',
          retailPrice: i % 3 === 0 ? '¥198' : i % 3 === 1 ? '¥128' : '¥98',
          discount: '8.0折',
          discountPrice: i % 3 === 0 ? '¥158' : i % 3 === 1 ? '¥102' : '¥78',
          buyer: '美世美容院',
          contact: '李娜',
          phone: '13900139000',
          buyNum: 30,
          retailTotal: i % 3 === 0 ? '¥5940' : i % 3 === 1 ? '¥3840' : '¥2940',
          dealPrice: i % 3 === 0 ? '¥4740' : i % 3 === 1 ? '¥3060' : '¥2340',
          payment: '支付宝'
        },
        {
          date: '2024.06.10',
          orderNo: 'XS20240610003',
          productName: i % 3 === 0 ? '韩束精华液' : i % 3 === 1 ? '韩束补水面膜' : '韩束BB霜',
          productNo: `HS-00${i % 3 + 1}`,
          spec: i % 3 === 0 ? '50ml' : i % 3 === 1 ? '10片' : '30g',
          retailPrice: i % 3 === 0 ? '¥198' : i % 3 === 1 ? '¥128' : '¥98',
          discount: '9.0折',
          discountPrice: i % 3 === 0 ? '¥178' : i % 3 === 1 ? '¥115' : '¥88',
          buyer: '盛世美颜会所',
          contact: '王敏',
          phone: '13700137000',
          buyNum: 15,
          retailTotal: i % 3 === 0 ? '¥2970' : i % 3 === 1 ? '¥1920' : '¥1470',
          dealPrice: i % 3 === 0 ? '¥2670' : i % 3 === 1 ? '¥1725' : '¥1320',
          payment: '银行转账'
        }
      ]
    })),
    week: Array.from({ length: 20 }, (_, i) => ({ 
      rank: i + 1, 
      name: i % 3 === 0 ? '韩束精华液' : i % 3 === 1 ? '韩束补水面膜' : '韩束BB霜', 
      code: `HS-00${i % 3 + 1}`, 
      spec: i % 3 === 0 ? '50ml' : i % 3 === 1 ? '10片' : '30g', 
      brand: '韩束', 
      sales: 8500 + i * 200, 
      amount: `¥${(850000 + i * 20000).toLocaleString()}`, 
      discount: `¥${(85000 + i * 2000).toLocaleString()}`,
      details: [
        {
          date: '2024.06.05',
          orderNo: 'XS20240605004',
          productName: i % 3 === 0 ? '韩束精华液' : i % 3 === 1 ? '韩束补水面膜' : '韩束BB霜',
          productNo: `HS-00${i % 3 + 1}`,
          spec: i % 3 === 0 ? '50ml' : i % 3 === 1 ? '10片' : '30g',
          retailPrice: i % 3 === 0 ? '¥198' : i % 3 === 1 ? '¥128' : '¥98',
          discount: '8.5折',
          discountPrice: i % 3 === 0 ? '¥168' : i % 3 === 1 ? '¥109' : '¥83',
          buyer: '陈泽美容院',
          contact: '陈泽',
          phone: '13800138000',
          buyNum: 50,
          retailTotal: i % 3 === 0 ? '¥9900' : i % 3 === 1 ? '¥6400' : '¥4900',
          dealPrice: i % 3 === 0 ? '¥8400' : i % 3 === 1 ? '¥5450' : '¥4150',
          payment: '微信支付'
        },
        {
          date: '2024.06.07',
          orderNo: 'XS20240607005',
          productName: i % 3 === 0 ? '韩束精华液' : i % 3 === 1 ? '韩束补水面膜' : '韩束BB霜',
          productNo: `HS-00${i % 3 + 1}`,
          spec: i % 3 === 0 ? '50ml' : i % 3 === 1 ? '10片' : '30g',
          retailPrice: i % 3 === 0 ? '¥198' : i % 3 === 1 ? '¥128' : '¥98',
          discount: '8.0折',
          discountPrice: i % 3 === 0 ? '¥158' : i % 3 === 1 ? '¥102' : '¥78',
          buyer: '美世美容院',
          contact: '李娜',
          phone: '13900139000',
          buyNum: 40,
          retailTotal: i % 3 === 0 ? '¥7920' : i % 3 === 1 ? '¥5120' : '¥3920',
          dealPrice: i % 3 === 0 ? '¥6320' : i % 3 === 1 ? '¥4080' : '¥3120',
          payment: '支付宝'
        }
      ]
    })),
    month: Array.from({ length: 25 }, (_, i) => ({ 
      rank: i + 1, 
      name: i % 3 === 0 ? '韩束精华液' : i % 3 === 1 ? '韩束补水面膜' : '韩束BB霜', 
      code: `HS-00${i % 3 + 1}`, 
      spec: i % 3 === 0 ? '50ml' : i % 3 === 1 ? '10片' : '30g', 
      brand: '韩束', 
      sales: 32000 + i * 500, 
      amount: `¥${(3200000 + i * 50000).toLocaleString()}`, 
      discount: `¥${(320000 + i * 5000).toLocaleString()}`,
      details: [
        {
          date: '2024.06.01',
          orderNo: 'XS20240601006',
          productName: i % 3 === 0 ? '韩束精华液' : i % 3 === 1 ? '韩束补水面膜' : '韩束BB霜',
          productNo: `HS-00${i % 3 + 1}`,
          spec: i % 3 === 0 ? '50ml' : i % 3 === 1 ? '10片' : '30g',
          retailPrice: i % 3 === 0 ? '¥198' : i % 3 === 1 ? '¥128' : '¥98',
          discount: '8.5折',
          discountPrice: i % 3 === 0 ? '¥168' : i % 3 === 1 ? '¥109' : '¥83',
          buyer: '陈泽美容院',
          contact: '陈泽',
          phone: '13800138000',
          buyNum: 100,
          retailTotal: i % 3 === 0 ? '¥19800' : i % 3 === 1 ? '¥12800' : '¥9800',
          dealPrice: i % 3 === 0 ? '¥16800' : i % 3 === 1 ? '¥10900' : '¥8300',
          payment: '银行转账'
        },
        {
          date: '2024.06.10',
          orderNo: 'XS20240610007',
          productName: i % 3 === 0 ? '韩束精华液' : i % 3 === 1 ? '韩束补水面膜' : '韩束BB霜',
          productNo: `HS-00${i % 3 + 1}`,
          spec: i % 3 === 0 ? '50ml' : i % 3 === 1 ? '10片' : '30g',
          retailPrice: i % 3 === 0 ? '¥198' : i % 3 === 1 ? '¥128' : '¥98',
          discount: '8.0折',
          discountPrice: i % 3 === 0 ? '¥158' : i % 3 === 1 ? '¥102' : '¥78',
          buyer: '美世美容院',
          contact: '李娜',
          phone: '13900139000',
          buyNum: 80,
          retailTotal: i % 3 === 0 ? '¥15840' : i % 3 === 1 ? '¥10240' : '¥7840',
          dealPrice: i % 3 === 0 ? '¥12640' : i % 3 === 1 ? '¥8160' : '¥6240',
          payment: '微信支付'
        }
      ]
    }))
  },
  set: { today: [], week: [], month: [] },
  project: { today: [], week: [], month: [] }
};

// 计算属性：基础数据
const baseData = computed(() => {
  return tableData[activeTab.value][activeDate.value] || [];
});

// 计算属性：筛选后数据
const filteredData = computed(() => {
  if (!searchKeyword.value) return baseData.value;
  const keyword = searchKeyword.value.trim();
  return baseData.value.filter(item => 
    item.name.includes(keyword)
  );
});

// 计算属性：分页数据
const pagedData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return filteredData.value.slice(startIndex, startIndex + pageSize.value);
});

// 弹窗明细计算
const totalBuyNum = computed(() => {
  if (!currentProduct.value?.details) return 0;
  return currentProduct.value.details.reduce((sum, item) => sum + item.buyNum, 0);
});

const totalRetailPrice = computed(() => {
  if (!currentProduct.value?.details) return '¥0';
  const total = currentProduct.value.details.reduce((sum, item) => {
    return sum + Number(item.retailTotal.replace('¥', ''));
  }, 0);
  return `¥${total.toLocaleString()}`;
});

const totalDealPrice = computed(() => {
  if (!currentProduct.value?.details) return '¥0';
  const total = currentProduct.value.details.reduce((sum, item) => {
    return sum + Number(item.dealPrice.replace('¥', ''));
  }, 0);
  return `¥${total.toLocaleString()}`;
});

// 筛选后明细计算
const filteredBuyNum = computed(() => {
  return filteredDetails.value.reduce((sum, item) => sum + item.buyNum, 0);
});

const filteredRetailPrice = computed(() => {
  const total = filteredDetails.value.reduce((sum, item) => {
    return sum + Number(item.retailTotal.replace('¥', ''));
  }, 0);
  return `¥${total.toLocaleString()}`;
});

const filteredDealPrice = computed(() => {
  const total = filteredDetails.value.reduce((sum, item) => {
    return sum + Number(item.dealPrice.replace('¥', ''));
  }, 0);
  return `¥${total.toLocaleString()}`;
});

// 监听产品变化，初始化明细数据
watch(currentProduct, (newVal) => {
  if (newVal?.details) {
    filteredDetails.value = [...newVal.details];
  } else {
    filteredDetails.value = [];
  }
  // 重置弹窗时间筛选
  dialogStartTime.value = '';
  dialogEndTime.value = '';
});

// 弹窗内时间筛选
const filterDetailData = () => {
  if (!currentProduct.value?.details) return;
  
  if (!dialogStartTime.value && !dialogEndTime.value) {
    filteredDetails.value = [...currentProduct.value.details];
    return;
  }

  const start = new Date(dialogStartTime.value);
  const end = new Date(dialogEndTime.value);
  
  filteredDetails.value = currentProduct.value.details.filter(item => {
    const itemDate = new Date(item.date.replace(/\./g, '-'));
    return itemDate >= start && itemDate <= end;
  });
};

// 弹窗内导出功能
const exportDetailData = () => {
  if (filteredDetails.value.length === 0) {
    ElMessage.warning('没有可导出的数据');
    return;
  }
  ElMessage.success('明细数据已导出为Excel');
};

// 原有方法
const handleTabChange = () => {
  currentPage.value = 1;
};
const handleDateChange = () => {
  currentPage.value = 1;
};
const handleSearch = () => {
  currentPage.value = 1;
};
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};
const handleCurrentChange = (page) => {
  currentPage.value = page;
};
const openDetail = (row) => {
  currentProduct.value = row;
  detailVisible.value = true;
};
</script>

<style scoped>
/* 基础样式 */
.sales-container {
  padding: 30px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 标题样式 */
.page-title {
  text-align: center;
  color: #4ecdc4;
  font-size: 26px;
  margin: 0 0 60px;
  font-weight: 700;
}

/* 前三名柱子样式 */
.top3-pillars {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 100px;
  margin-bottom: 60px;
  height: 320px;
  position: relative;
  padding-bottom: 30px;
}

/* 柱子容器 */
.pillar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 240px;
}

/* 排名文字 */
.rank-text {
  color: #666;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
  width: 100%;
}

/* 柱子本体 */
.pillar-body {
  background: #f5f5f5;
  border-radius: 8px 8px 0 0;
  width: 100%;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  padding: 25px 0;
  font-weight: 700;
}

/* 柱子高度区分 */
.first-pillar .pillar-body {
  height: 250px;
}

.second-pillar .pillar-body {
  height: 200px;
}

.third-pillar .pillar-body {
  height: 170px;
}

/* 柱子内产品信息 */
.product-info {
  color: #4ecdc4;
  text-align: center;
  line-height: 1.8;
}

.brand {
  font-size: 20px;
  margin: 0 0 8px;
}

.name {
  font-size: 18px;
  margin: 0 0 8px;
}

.price, .total {
  font-size: 16px;
  margin: 0;
}

/* 标签栏样式 */
.sales-tabs {
  margin-bottom: 20px;
  --el-tabs-active-color: #4ecdc4;
  --el-tabs-nav-item-active-bg-color: #f5f5f5;
}

/* 筛选栏样式 */
.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.date-filter {
  --el-radio-button-active-color: #4ecdc4;
  --el-radio-button-active-bg-color: #f5f5f5;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-label {
  color: #666;
  font-size: 14px;
}

.search-input {
  width: 200px;
}

.search-btn {
  background-color: #4ecdc4;
  border-color: #4ecdc4;
}

/* 表格样式 */
.sales-table {
  --el-table-header-text-color: #666;
  --el-table-body-text-color: #666;
  --el-table-border-color: #e0e0e0;
  margin-bottom: 20px;
}

.sales-table th,
.sales-table td {
  text-align: center !important;
}

.detail-btn {
  background-color: #4ecdc4;
  color: white;
  border: none;
  padding: 5px 12px;
  border-radius: 4px;
  font-size: 12px;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
  --el-pagination-item-active-color: #4ecdc4;
  --el-pagination-item-active-bg-color: #f5f5f5;
}

/* 明细弹窗样式 */
.detail-content {
  margin-top: 10px;
}

.detail-total {
  font-size: 14px;
}

/* 弹窗产品基本信息样式 */
.product-base-info p {
  margin: 5px 0;
  color: #666;
}
</style>